package com.example.smartcitymovie.ui.selfcenter;

import android.app.ActionBar;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.navigation.Navigation;
import androidx.room.Room;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.smartcitymovie.R;
import com.example.smartcitymovie.dao.AppDatabase;
import com.example.smartcitymovie.dao.Userdao;
import com.example.smartcitymovie.databinding.FragmentRegisterBinding;
import com.example.smartcitymovie.entity.User;

import java.util.Objects;

import cn.hutool.crypto.digest.MD5;


public class RegisterFragment extends Fragment {

    FragmentRegisterBinding fragmentRegisterBinding;

    private Userdao userdao;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        fragmentRegisterBinding = FragmentRegisterBinding.inflate(getLayoutInflater());
        setHasOptionsMenu(true);
        AppDatabase db = Room.databaseBuilder(requireActivity(),
                AppDatabase.class, "database").build();
        userdao = db.userDao();
        init();
        return fragmentRegisterBinding.getRoot();
    }

    public void init() {
        fragmentRegisterBinding.btnReg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MD5 md5 = MD5.create();
                User user = new User();
                user.setAvatar("");
                user.setNickName(fragmentRegisterBinding.TIETNickName.getText().toString());
                user.setUserName(fragmentRegisterBinding.TIETUserName.getText().toString());
                user.setSex(1);
                user.setPassword(md5.digestHex(fragmentRegisterBinding.TIETPassword.getText().toString()));
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        userdao.insertAll(user);
                       requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(), "注册成功", Toast.LENGTH_SHORT).show());
                    }
                }).start();
            }
        });

        fragmentRegisterBinding.btnGoLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Navigation.findNavController(requireActivity(), R.id.nav_host_fragment_activity_main).navigate(R.id.action_navication_registerFragment_to_navigation_Login);
            }
        });
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
    }
}